package ch.usi.inf.pf2.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * 
 * @author Lorenzo Baracchi <lorenzo.baracchi@usi.ch>, Ebrisa Savina Mastrodicasa
 *
 */
public class InsertConstantWindow
{
    private JFrame constantFrame;
    private JPanel panel;
    private JSpreadSheetGUI spreadTable;

    public InsertConstantWindow (JSpreadSheetGUI spreadTable)
    {
	   this.spreadTable=spreadTable;
	   constantFrame= new JFrame("Insert Constant in the cell");
	   makeFrame();
    }
    
    public void makeFrame ()
    {
	   constantFrame.setLocationRelativeTo(spreadTable.getFrame());
	   constantFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	   constantFrame.getContentPane().setLayout(new BorderLayout());
	   panel = new JPanel();
	   panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
	   makeDropDown();
	   constantFrame.getContentPane().add(panel, BorderLayout.CENTER);
	   constantFrame.pack();
	   constantFrame.setVisible(true);
    }
    
    public void makeDropDown ()
    {
	   final JComboBox combo = new JComboBox(possibleConstants());
	   combo.setSelectedIndex(0);
	   panel.add(combo);
	   
	   final JLabel label = new JLabel("Insert a mathematical constant");
	   panel.add(label);
	   
	   final JButton ok = new JButton("Insert");
	   panel.add(ok);
	   ok.addActionListener(new ActionListener()
	   {
	       
	       @Override
	       public void actionPerformed(ActionEvent arg0)
	       {
	   	   	double returnValue= computeReturn((String)combo.getSelectedItem());
	   	   	String actualText = spreadTable.getTextField().getText();
	   	   	int cursorPosition = spreadTable.getTextField().getCaretPosition();
	   	   	String tmp = actualText.substring(cursorPosition, actualText.length());
	   	   	actualText = actualText.substring(0, cursorPosition)+ returnValue +tmp;
	   	   	spreadTable.getTextField().setText(actualText);
	   	   	constantFrame.dispose();
	       }
	   });
    }
    
    public String[] possibleConstants ()
    {
	   String[] s= {"\u03C0", "\u03C0/2", "\u03C0/3", "\u03C0/4", "\u03C0/6", "e", "c", "\u03C6", "\u221A2"};
	   return s;
    }
    
    public double computeReturn (String s)
    {
	   if(s == "\u03C0")
		  return Math.PI;
	   else if (s== "\u03C0/2")
		  return Math.PI/2;
	   else if (s== "\u03C0/3")
		  return Math.PI/3;
	   else if (s== "\u03C0/4")
		  return Math.PI/4;
	   else if (s== "\u03C0/6")
		  return Math.PI/6;
	   else if (s== "e")
		  return Math.E;
	   else if (s== "c")
		   return 299792458.0;
	   else if (s == "\u03C6")
		   return 1.61803398874989484820458683436563811;
	   else if (s == "\u221A2")
		   return 1.41421356237309504880168872420969807; 
	   return 0;
    }
}
